package com.sci.web.controller.common;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.sci.config.MyConstants;
import com.sci.web.controller.BaseController;
import com.sci.web.dao.FileUploadfileinfDao;
import com.sci.web.model.dto.FullAvatarDto;
import com.sci.web.model.dto.PageDto;
import com.sci.web.model.genmodel.FileUploadfileinf;
import com.sci.web.model.genmodel.SysEnums;
import com.sci.web.model.genmodel.User;
import com.sci.web.service.common.FileClientService;
import com.sci.web.util.CommMethod;
import com.sci.web.util.StringUtil;

public class FileClientController extends BaseController {

	
	public FileClientService fileClientService = new FileClientService();
	
	
	
	
	/**
	* @Title: uploadFile
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param     参数
	* @return void    返回类型
	* @throws
	*/
	public void uploadFile(){
		
		//Object sessionAttr = (User)getSessionAttr("user");
		UploadFile file = getFile();
		String realPath = getSession().getServletContext().getRealPath(String.valueOf(File.separatorChar));
		User user = super.getSessionByUser();
		if(user!=null){
			String uploadFile = fileClientService.uploadFile(file, user , realPath);
			if(uploadFile!=null){
				Map<String , String> map = new HashMap<String, String>();
				FileUploadfileinf fileUploadfileinf = FileUploadfileinfDao.me.geetFileUploadfileinfById(uploadFile);
				String url = "http://www.lexy.ga/"+MyConstants.FILE_PATH_ADMIN+fileUploadfileinf.getFdirectory()+File.separator+fileUploadfileinf.getFileName();
				map.put("imgUrl", url);
				map.put("oldName", fileUploadfileinf.getFileShowName());
				success(map);
			}
		}else{
			
		}
	}
	
	
	
	
	/**
	* @Title: getFileList
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param     参数
	* @return void    返回类型
	* @throws
	*/
	public void getFileList(){
		List<Map<String, String>> fileList = fileClientService.getFileList("admin");
		success(fileList);
	}
	
	
	
	 public void uploadFullAvatar(){
		 
		 FullAvatarDto uploadFullAvatar = null;
		 
		 // 获取路径
		 String rootPath = getSession().getServletContext().getRealPath(String.valueOf(File.separatorChar));
		 rootPath = rootPath.substring(0, rootPath.indexOf("lexy_blog"));
		 
		 
		 HttpServletRequest request = getRequest();
		String contentType = request.getContentType();
		 if (contentType.indexOf("multipart/form-data") >= 0 ) {
			 uploadFullAvatar = fileClientService.uploadFullAvatar(request , rootPath);
		 }
		 
		 
		 /*FullAvatarDto result = new FullAvatarDto();
		 result.avatarUrls = new ArrayList();
		 result.success = false;
		 result.msg = "Failure!";
		 String fileName = UUID.randomUUID().toString().replaceAll("-", "");
		 

		 
		 
		 FileItemFactory factory = new DiskFileItemFactory();
		 ServletFileUpload upload = new ServletFileUpload(factory);
		 FileItemIterator fileItems = upload.getItemIterator(request);
		 
         //定义一个变量用以储存当前头像的序号
         int avatarNumber = 1;
         //遍历所有文件域
        
         
       //基于原图的初始化参数
     	String initParams = "";
     	BufferedInputStream	inputStream;
     	BufferedOutputStream outputStream;
     	//遍历表单域
     	while( fileItems.hasNext() ){
     		FileItemStream fileItem = fileItems.next();
    		String fieldName = fileItem.getFieldName();
    		//是否是原始图片 file 域的名称（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）
    		Boolean isSourcePic = fieldName.equals("__source");
    		//文件名，如果是本地或网络图片为原始文件名（不含扩展名）、如果是摄像头拍照则为 *FromWebcam
    		//String name = fileItem.getName();
    		//当前头像基于原图的初始化参数（即只有上传原图时才会发送该数据），用于修改头像时保证界面的视图跟保存头像时一致，提升用户体验度。
    		//修改头像时设置默认加载的原图url为当前原图url+该参数即可，可直接附加到原图url中储存，不影响图片呈现。
    		if ( fieldName.equals("__initParams") )
    		{
    			inputStream = new BufferedInputStream(fileItem.openStream());
    			byte[] bytes = new byte [inputStream.available()];
    			inputStream.read(bytes);
    			initParams = new String(bytes, "UTF-8");
    			inputStream.close();
    		}
    		//如果是原始图片 file 域的名称或者以默认的头像域名称的部分“__avatar”打头
    		else if ( isSourcePic || fieldName.startsWith("__avatar") )
    		{
    			String virtualPath = "/upload/jsp_avatar" + avatarNumber + "_" + fileName + ".jpg";
    			//原始图片（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）。
    			if( isSourcePic )
    			{
    				result.sourceUrl = virtualPath = "/upload/jsp_source_" + fileName + ".jpg";
    			}
    			//头像图片（默认的 file 域的名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names）。
    			else
    			{
    				result.avatarUrls.add(virtualPath);
    				avatarNumber++;
    			}
    			inputStream = new BufferedInputStream(fileItem.openStream());
    			outputStream = new BufferedOutputStream(new FileOutputStream(application.getRealPath("/") + virtualPath.replace("/", "\\")));
    			Streams.copy(inputStream, outputStream, true);
    			inputStream.close();
                outputStream.flush();
                outputStream.close();
    		}
     	}
         
         
         
         result.success = true;
         result.msg = "Success!";
         //返回图片的保存结果（返回内容为json字符串，可自行构造，该处使用Newtonsoft.Json构造）
         //  Response.Write(JsonConvert.SerializeObject(result));
*/        
		 
		 success(uploadFullAvatar);
     }
	
	
	
	
	 
	 
	 /**  
	* @Title: getUploadFileInfPageInate  
	* @Description:    
	* @returnType void      
	* @author LiuFei
	* @date 下午1:56:01
	* @throws  
	*/
	public void getUploadFileInfPageInate(){
			PageDto page = new PageDto();
			Integer draw = getParaToInt("draw");
			Integer start = getParaToInt("start");
			Integer length = getParaToInt("length");
			String searchVal = super.getParameter("search[value]");
		
			
			 //Page<BlogContent> blogPageInit = blogContentService.getBlogPageInit(user.getUserNo(), searchVal, (start/length)+1 , length);
			Integer pageSize = 15;
			
			if( length==null  ){
				String  DataTablePageSize = CommMethod.getSysEnumsByKeyToValue("DataTablePageSize");
				length = StringUtil.isEmpty(DataTablePageSize)?pageSize:Integer.parseInt(DataTablePageSize);
			}
			
			
			start = start==0?1:start/length;
			Page<FileUploadfileinf> fileUploadfileinfPageInate = fileClientService.getFileUploadfileinfPageInate(start, length, searchVal, "");
			List<FileUploadfileinf> resultList = new ArrayList<FileUploadfileinf>();
			if(fileUploadfileinfPageInate!=null){
				String webDomainName = CommMethod.getSysEnumsByKeyToValue("webDomainName");
				String fileWebName = CommMethod.getSysEnumsByKeyToValue("fileWebName");
				for (FileUploadfileinf entity : fileUploadfileinfPageInate.getList()) {
					System.out.println(entity.getThumbPath());
					entity.setThumbPath(webDomainName+File.separator+ fileWebName +File.separator+entity.getThumbPath());
					entity.setFilePath(webDomainName+File.separator+ fileWebName +File.separator+entity.getFilePath());
					resultList.add(entity);
				}
				//resultList ,
			}
			page.setDraw(draw);
			page.setRecordsTotal(fileUploadfileinfPageInate.getTotalRow());
			page.setRecordsFiltered(fileUploadfileinfPageInate.getTotalRow());
			page.setData(resultList);
			renderJson(page);
		}
	
	
	
	public void getFilePageInate(){
		User user = super.getSessionByUser();
		int pageNumber = super.getBaseParToInt("p");
		String sysEnumsByKeyToValue = CommMethod.getSysEnumsByKeyToValue("pageSize");
		int pageSize =sysEnumsByKeyToValue==null? 0: Integer.parseInt(sysEnumsByKeyToValue);
		String fileType = super.getBasePara("filetype");
		String searchStr = super.getBasePara("searchstr");
		Page<FileUploadfileinf> fileUploadfileinfPageInint = null;
		if(user!=null){
			pageNumber = pageNumber==0?1:pageNumber;
			Page<FileUploadfileinf> fileList = fileClientService.getFileUploadfileinfPageInate(pageNumber, pageSize, fileType, searchStr);
			if(fileList!=null){
				List<FileUploadfileinf> resultList = new ArrayList<FileUploadfileinf>();
				String webDomainName = CommMethod.getSysEnumsByKeyToValue("webDomainName");
				String fileWebName = CommMethod.getSysEnumsByKeyToValue("fileWebName");
				for (FileUploadfileinf entity : fileList.getList()) {
					System.out.println(entity.getThumbPath());
					entity.setThumbPath(webDomainName+File.separator+ fileWebName +File.separator+entity.getThumbPath());
					entity.setFilePath(webDomainName+File.separator+ fileWebName +File.separator+entity.getFilePath());
					resultList.add(entity);
				}
				//resultList ,
				fileUploadfileinfPageInint = new Page<FileUploadfileinf>(resultList , fileList.getPageNumber() , fileList.getPageSize() , fileList.getTotalPage() , fileList.getTotalRow());
			}
			success(fileUploadfileinfPageInint);
		}else{
			redirect("/v2/admin");
		}
	}
	
	
}
